import { read } from '../Httpaxios/http';
import * as signalR from '@microsoft/signalr';
import { useCounterStore } from '../stores/counter'; 

// 确保在 setup 或组件内部使用
const store = useCounterStore();
// ...existing code...
console.log("查看患者姓名",store.useStore.userName);

export interface Message {
  id: string;
  content: string;
  senderId: string;
  receiverId: string;
  timestamp: number;
  status: 'sent' | 'delivered' | 'read';
}

export interface ChatContact {
  id: string;
  name: string;
  avatar: string;
  lastMessage?: string;
  unreadCount: number;
  lastActiveTime: number;
}

// SignalR连接实例
let hubConnection: signalR.HubConnection | null = null;

/**
 * 创建SignalR连接
 */
export const createSignalRConnection = (): signalR.HubConnection => {
  if (hubConnection && hubConnection.state === signalR.HubConnectionState.Connected) {
    return hubConnection;
  }

  hubConnection = new signalR.HubConnectionBuilder()
    .withUrl('http://localhost:5260/api/chatHub')
    .withAutomaticReconnect()
    .build();

  return hubConnection;
};

/**
 * 启动SignalR连接
 */
export const startSignalRConnection = async (): Promise<void> => {
  try {
    const connection = createSignalRConnection();
    if (connection.state !== signalR.HubConnectionState.Connected) {
      await connection.start();
      console.log('SignalR连接成功');
    }
  } catch (error) {
    console.error('SignalR连接失败:', error);
    throw error;
  }
};

/**
 * 获取聊天联系人列表
 */
export const getChatContacts = async (userId: string): Promise<ChatContact[]> => {
  try {
    const response = await read.get('/Patient/GetChatListItem', {
      params: { 
        UserName: store.useStore.userName,
        Role: 1  // 1表示患者
      }
    });
    
    console.log('患者端API原始响应数据:', response.data);
    
    // 检查响应数据是否有效
    if (!response.data || !response.data.data || !Array.isArray(response.data.data) || response.data.data.length === 0) {
      console.log('没有获取到聊天列表数据，使用模拟数据');
      return [
        {
          id: '1',
          name: '王大夫',
          avatar: 'https://dummyimage.com/40x40/FFA500/fff',
          lastMessage: '您好，请问有什么可以帮助您？',
          unreadCount: 1,
          lastActiveTime: Date.now() - 1000 * 60 * 5
        }
      ];
    }
    
    // 有效数据，进行转换
    const rawList = response.data.data;
    return rawList.map((item: any) => ({
      id: String(item.chatListItemID),
      name: item.contactName,
      avatar: item.avatar || 'https://dummyimage.com/40x40/FFA500/fff',
      lastMessage: item.messageContent,
      unreadCount: item.hasRedDot ? 1 : 0,
      lastActiveTime: new Date(item.chatTime).getTime()
    }));
  } catch (error) {
    console.error('获取聊天联系人列表失败:', error);
    // 错误时返回模拟数据
    return [
      {
        id: '1',
        name: '王大夫',
        avatar: 'https://dummyimage.com/40x40/FFA500/fff',
        lastMessage: '您好，请问有什么可以帮助您？',
        unreadCount: 1,
        lastActiveTime: Date.now() - 1000 * 60 * 5
      }
    ];
  }
};

/**
 * 获取聊天历史记录
 */
export const getChatHistory = async (
  userId: string,
  contactId: string,
  limit: number = 50
): Promise<Message[]> => {
  try {
    const response = await read.get('/Patient/GetChatHistory', {
      params: {
        UserId: userId,
        ContactId: contactId,
        Limit: limit
      }
    });
    
    // 如果没有数据，提供模拟数据
    if (!response.data.data || response.data.data.length === 0) {
      console.log('没有获取到聊天历史数据，使用模拟数据');
      return [
        {
          id: '1',
          content: '患者您好，请问有什么不舒服？',
          senderId: contactId,
          receiverId: userId,
          timestamp: Date.now() - 1000 * 60 * 10,
          status: 'read'
        }
      ];
    }
    
    const rawList = response.data.data || [];
    return rawList.map((item: any) => ({
      id: String(item.messageId || item.chatListItemID),
      content: item.content || item.chatMessage,
      senderId: item.senderId || item.sender,
      receiverId: item.receiverId || item.contactName,
      timestamp: new Date(item.timestamp || item.chatTime).getTime(),
      status: item.status || (item.hasRedDot ? 'delivered' : 'read')
    }));
  } catch (error) {
    console.error('获取聊天历史记录失败:', error);
    // 出错时返回模拟数据
    return [
      {
        id: '1',
        content: '患者您好，请问有什么不舒服？',
        senderId: contactId,
        receiverId: userId,
        timestamp: Date.now() - 1000 * 60 * 10,
        status: 'read'
      }
    ];
  }
};

/**
 * 标记消息为已读
 */
export const markMessagesAsRead = async (messageIds: string[]): Promise<void> => {
  try {
    await read.post('/Patient/MarkMessagesAsRead', {
      messageIds
    });
  } catch (error) {
    console.error('标记消息已读失败:', error);
  }
};

/**
 * 发送私聊消息
 */
export const sendPrivateMessage = async (
  receiverId: string,
  message: string
): Promise<void> => {
  const connection = createSignalRConnection();
  
  if (connection.state !== signalR.HubConnectionState.Connected) {
    await startSignalRConnection();
  }

  try {
    await connection.invoke('SendPrivateMessage', receiverId, message);
  } catch (error) {
    console.error('发送消息失败:', error);
    throw error;
  }
};

/**
 * 设置消息接收处理
 */
export const setupMessageHandlers = (
  userId: string,
  onMessageReceived: (message: Message) => void,
  onConnectionEstablished?: () => void,
  onError?: (error: any) => void
): void => {
  const connection = createSignalRConnection();
  
  // 接收私聊消息
  connection.on('ReceivePrivateMessage', (message: any) => {
    onMessageReceived({
      id: Date.now().toString(),
      content: message.Message,
      senderId: message.SenderId,
      receiverId: userId,
      timestamp: new Date(message.Timestamp).getTime(),
      status: 'delivered'
    });
  });
  
  // 连接成功
  connection.on('Connected', (data: any) => {
    console.log('SignalR连接成功:', data);
    if (onConnectionEstablished) {
      onConnectionEstablished();
    }
  });
  
  // 错误处理
  connection.onclose((error) => {
    console.error('SignalR连接关闭:', error);
    if (onError) {
      onError(error);
    }
  });
}; 